/*
* 示例 1:

  输入: nums1 = [1,2,2,1], nums2 = [2,2]
  输出: [2,2]
  示例 2:

  输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
  输出: [4,9]
  https://leetcode-cn.com/problems/intersection-of-two-arrays-ii
* */

const nums1 = [1, 2, 3, 2];
const nums2 = [2, 3, 3, 2];

console.log(insertNums(nums1, nums2));

function insertNums(nums1, nums2) {
  const map1 = createMap(nums1);
  const map2 = createMap(nums2);
  const res = [];

  // for of遍历map 的key
  for (const num of map1.keys()) {
    // console.log(num);
    let count1 = map1.get(num);
    let count2 = map2.get(num);
    // 找出两个map中出现次数最小的个数，放入到新数组当中
    if (count2) {
      const count = Math.min(count1, count2);
      const result = String.prototype.repeat.call(num, count).split('');
      res.push(...result);
    }
  }

  return res;
}

function createMap(nums) {
  //构建map结构，记录出现的次数
  let map = new Map();

  nums.forEach((num) => {
    const count = map.get(num);

    map.set(num, count ? count + 1 : 1);
  });

  return map;
}
